<?php
$con    = new MongoDB\Driver\Manager('mongodb://192.168.204.129:27017');
//$query  = new MongoDB\Driver\Query([]);
//$cursor = $con->executeQuery('databaseName.collectionName',$query);
//var_dump($cursor);
//$it     = new IteratorIterator($cursor);
//$it->rewind();
//while ($doc=$it->current())
//{   print\_r($doc);   $it->next();
//}

$bulk = new MongoDB\Driver\BulkWrite();
$id1 = $bulk->insert([
    'product_id'        => 101,
    'product_name'      => '俱乐部全犬种成犬粮天然健康狗粮10kg',
    'product_price'     => 269.00,
    'created_at' => new MongoDB\BSON\UTCDateTime(),
]);
$id2 = $bulk->insert([
    'product_id'        => 102,
    'product_name'      => '泰迪成犬粮专用狗粮2.5kg',
    'product_price'     => 245.00,
    'created_at' => new MongoDB\BSON\UTCDateTime(),
]);
$id3 = $bulk->insert([
    'product_id'        => 103,
    'product_name'      => '中小型成犬粮牛肉蔬菜狗粮500g',
    'product_price'     => 14.00,
    'created_at' => new MongoDB\BSON\UTCDateTime(),
]);

var_dump('--> ID 1 是： ' . $id1);
var_dump('--> ID 2 是： ' . $id2);
var_dump('--> ID 3 是： ' . $id3);

try {
    $result = $con ->executeBulkWrite('testdb.products', $bulk);
    var_dump($result->getInsertedCount());
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteErrors());
}
$filter = ['product_price' => ['$gt' => 100]];
$options = [
    'projection' => ['_id' => 0],
    'sort' => ['product_price' => 1],
];

$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $con->executeQuery('testdb.products', $query);

foreach ($cursor as $document) {
    print_r($document);
}




$filters = ['product_id' => 103];
$sets = ['$set' => ['product_price' => 111.22]];
$updateOptions = ['multi' => false, 'upsert' => false];
$bulk->update($filters, $sets, $updateOptions);


$filters = ['product_id' => 101];
$bulk->delete($filters);

try {
    $result = $con->executeBulkWrite('testdb.products', $bulk);
    var_dump('修改影响的条数: ' . $result->getModifiedCount());
    var_dump('删除影响的条数: ' . $result->getDeletedCount());
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
    var_dump($e->getWriteResult()->getWriteErrors());
}
?>